package com.dkm.controller;

import java.io.UnsupportedEncodingException;

import javax.security.auth.login.AccountLockedException;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dkm.entity.Users;
import com.dkm.service.UsersService;
import com.dkm.util.RedisUtil;
import com.dkm.util.ResultUtil;
import com.dkm.util.TokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;

@RestController
@RequestMapping("/index")
public class LoginController {

	@Autowired
	private UsersService usersService;
	
	@Autowired
	private RedisUtil redisUtil;
	
	@PostMapping("/login")
	public ResultUtil login(String login_name,String password) {
		
		//获取subject操作主体
		Subject subject=SecurityUtils.getSubject();
		
		//设置登录的用户名和密码
		UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(login_name, password);
		String token=null;
		try {
			subject.login(usernamePasswordToken);
			//获取操作主体
			Users user=(Users)subject.getPrincipal();
			//创建新的用户
			Users u=new Users();
			u.setLogin_name(user.getLogin_name());
			
			//生成token
			try {
				token=TokenUtil.sign(u, 1*60*60*100);
				System.out.println("token=>"+token);
				
				//存入redis
				redisUtil.set(u.getLogin_name(), token, 1*60*60*100);
				
			} catch (UnsupportedEncodingException | JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return new ResultUtil(0, token, subject.getPrincipal());
		} catch (UnknownAccountException e) {
			return new ResultUtil(-1, "该用户不存在！", null);
		} catch (LockedAccountException e) {
			System.out.println("locked");
			return new ResultUtil(-1, "账户已被锁定！", null);
		}catch (IncorrectCredentialsException e) {
			return new ResultUtil(-1, "密码错误！", null);
		}
		
	}
	
	@GetMapping("/logout")
	public ResultUtil logout() {
		//获取subject操作主体
		Subject subject=SecurityUtils.getSubject();
		
		try {
			subject.logout();
			return new ResultUtil(0, "退出成功！", null);
		} catch (Exception e) {
			return new ResultUtil(-1, "退出失败！", null);
		}
	}
}
